package Network

import (
	"SQL/db"
	"SQL/myDB"
	"SQL/util"
	"database/sql"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"logs"
	"net/http"
	"time"
)

var dbQueue chan *sql.DB

type Config struct {
	Debug           bool   `json::"debug"`
	ResetDB         bool   `json::"resetDB"`
	CopyDB          bool   `json::"copyDB"`
	Socket          string `json::"socket"`
	Postgresql      string `json::"postgresql"`
	MaxDBConnection int    `json::"maxDBConnection"`
	CopyDataNum     int    `json::"copyDataNum"`
}

var config Config

func openDB() *sql.DB {
	return <-dbQueue
}
func closeDB(db *sql.DB) {
	dbQueue <- db
}
func launchDB() {

	var err error
	dbQueue = make(chan *sql.DB, config.MaxDBConnection)
	for i := 0; i < config.MaxDBConnection; i++ {
		db, err := sql.Open("postgres", config.Postgresql)
		if err != nil {
			panic(err)
		}
		dbQueue <- db
	}
	logs.Print("open", len(dbQueue), "db", "success")
	//--------------------------------------------------dy
	myDB.Init(dbQueue)
	//--------------------------------------------------Ficow Shen
	ficowInit(dbQueue)

	//--------------------------------------------------Pismery
	util.Init(dbQueue)

	//--------------------------------------------------Decaf
	db.Init(dbQueue)

	if config.ResetDB {
		err = resetDB("resetDB")
		if err != nil {
			panic(err)
		}
	}
	if config.CopyDB {
		err = resetDB("copyDB")
		if err != nil {
			panic(err)
		}
	}
}
func OnlineNum() {
	logs.Print(onlineNum(), "are", "online")
	time.AfterFunc(time.Second*20, OnlineNum)
}

func LaunchRouter() {

	configBytes, err := ioutil.ReadFile("emb.config")
	if err != nil {
		panic(err)
	}
	err = json.Unmarshal(configBytes, &config)
	fmt.Println(config)
	if err != nil {
		panic(err)
	}
	logs.SetMode(config.Debug)
	launchDB()
	OnlineNum()

	r := &router{}
	http.ListenAndServe(config.Socket, r)
}
